// 添加好友、删除好友等
import { Request, Response, NextFunction } from 'express';
import * as friendService from '../services/friend.service';
import { FriendRequestDTO } from '../dto/friend.dto';
import { mqttClient } from '../config/mqtt';

export const sendRequest = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const input = FriendRequestDTO.parse(req.body);
    await friendService.sendFriendRequest((req as any).user, input);
    res.safeJson(null, '好友请求已发送');
    // mqttClient.publish
  } catch (err) {
    next(err);
  }
};

export const acceptRequest = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const uid = Number((req as any).user.id);
    const requestId = Number(req.body?.request_id);
    await friendService.acceptFriendRequest(uid, requestId);
    res.safeJson(null, '已接受好友请求');
  } catch (err) {
    next(err);
  }
};

export const listFriends = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const uid = Number((req as any).user.id);
    const friends = await friendService.getFriendList(uid);
    res.safeJson(friends, '获取成功');
  } catch (err) {
    next(err);
  }
};

export const listRequests = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const uid = Number((req as any).user.id);
    const requests = await friendService.getFriendRequests(uid);
    res.safeJson(requests, '获取成功');
  } catch (err) {
    next(err);
  }
};

export const removeFriend = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const uid = Number((req as any).user.id);
    const targetId = Number(req.params.id);
    await friendService.deleteFriend(uid, targetId);
    res.safeJson(null, '好友已删除');
  } catch (err) {
    next(err);
  }
};
